<?php

namespace control;

/*
*发货管理类
*/


class deliveryManageClass extends adIndexClass
{
    private const title = '发货管理';
    private const page = 'deliveryManage';
    private const table = 'delivery_order';
    private const tableMx = 'delivery_order_detail';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'signSearch':
                $tr = [
                    'orderNo'          => [
                        'name'  => '发货单号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'sales_contract' => [
                        'name'  => "合同名称",
                        'width' => 150,
                    ],
                    'companyName'  => [
                        'name'  => "客户",
                        'width' => 200,
                    ],
                    'contactName'  => [
                        'name'  => "收货人",
                        'width' => 150,
                    ],
                    'contactTel'  => [
                        'name'  => "联系电话",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'address'         => [
                        'name'  => '收货地址',
                        'width' => 100,
                    ],
                    'carInfo'         => [
                        'name'  => '车辆信息',
                        'width' => 100,
                    ],
                    'total'          => [
                        'name'  => '发货吨数',
                        'width' => 180,
                    ],
                    'send_date'          => [
                        'name'  => '发货日期',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'receipt_date'          => [
                        'name'  => '回单日期',
                        'width' => 180,
                        'sort' => 1,
                    ]
                ];
                break;
            case 'deliverySearch':
                $tr = [
                    'orderNo'          => [
                        'name'  => '发货单号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'sales_contract' => [
                        'name'  => "合同名称",
                        'width' => 150,
                    ],
                    'companyName'  => [
                        'name'  => "客户",
                        'width' => 200,
                    ],
                    'contactName'  => [
                        'name'  => "收货人",
                        'width' => 150,
                    ],
                    'contactTel'  => [
                        'name'  => "联系电话",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'address'         => [
                        'name'  => '收货地址',
                        'width' => 100,
                    ],
                    'carInfo'         => [
                        'name'  => '车辆信息',
                        'width' => 100,
                    ],
                    'delivery_manage'         => [
                        'name'  => '负责人',
                        'width' => 100,
                    ],
                    'total'          => [
                        'name'  => '发货吨数',
                        'width' => 180,
                    ],
                    'send_date'          => [
                        'name'  => '发货日期',
                        'width' => 180,
                        'sort' => 1,
                    ]
                ];
                break;
            case 'alreadySearch':
                $tr = [
                    'orderNo'          => [
                        'name'  => '发货单号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'sales_contract' => [
                        'name'  => "合同名称",
                        'width' => 150,
                    ],
                    'companyName'  => [
                        'name'  => "客户",
                        'width' => 200,
                    ],
                    'contactName'  => [
                        'name'  => "收货人",
                        'width' => 150,
                    ],
                    'contactTel'  => [
                        'name'  => "联系电话",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'address'         => [
                        'name'  => '收货地址',
                        'width' => 100,
                    ],
                    'carInfo'         => [
                        'name'  => '车辆信息',
                        'width' => 100,
                    ],
                    'delivery_manage'         => [
                        'name'  => '负责人',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '发货数',
                        'width' => 180,
                    ],
                    'weight'          => [
                        'name'  => '发货吨数',
                        'width' => 180,
                    ],
                    'carsWeight'          => [
                        'name'  => '核载吨数',
                        'width' => 180,
                    ],
                    'time'          => [
                        'name'  => '单据日期',
                        'width' => 180,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '发货单号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'sales_contract' => [
                        'name'  => "合同名称",
                        'width' => 150,
                    ],
                    'companyName'  => [
                        'name'  => "客户",
                        'width' => 200,
                    ],
                    'contactName'  => [
                        'name'  => "收货人",
                        'width' => 150,
                    ],
                    'contactTel'  => [
                        'name'  => "联系电话",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'address'         => [
                        'name'  => '收货地址',
                        'width' => 100,
                    ],
                    'manager'          => [
                        'name'  => '销售员',
                        'width' => 200,
                    ],
                    'weight'          => [
                        'name'  => '发货吨数',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'num'          => [
                        'name'  => '派车数',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'time'          => [
                        'name'  => '单据日期',
                        'width' => 180,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow): string
    {
        $array = [
            [
                [
                    "发货单号" => text(array("name" => "orderNo")),
                    "合同名称"   => text(array("name" => "contractName")),
                    "客户"   => text(array("name" => "unitA")),
                ],
                [
                    "收货人"   => text(array("name" => "contactName")),
                    "联系电话"   => text(array("name" => "contactTel")),
                    "收货地址"   => text(array("name" => "address")),
                ],
                [
                    '客户名称' => clientProfileClass::kehuSelect(array('title' => '')),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ];
        if($workFlow != '待派车'){
            $array[0][2]['车辆信息'] = text(array("name" => "carInfo"));
        }else{
            $array[0][2]['销售负责人'] = selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']);
        }
        return $this->tableShow($array,1);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('待派车');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*发货列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        $button = "";
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*发货列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "orderNo"     => $this->post('orderNo'),
            "contactName" => $this->post('contactName'),
            "contactTel"  => $this->post('contactTel'),
            "address"     => $this->post('address'),
        );
        //全等查询数组
        $equal = array(
            'coid'       => self::$coid,
            'send_state' => 0,  //待派车
            "manager"    => $this->post('stid'),
        );

        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'));
        }
        if ($this->post('contractName')) {
            $and2 = " and name like '%" . $this->post('contractName') . "%' ";
            $and  .= " and contractId in (select id from sales_contract where 1=1 {$and2}) ";
        }
        if ($this->post('unitA')) {
            $and .= " and khid in (select khid from kehu where companyName like '%" . $this->post('unitA') . "%') ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page  = $this->page(array("table" => self::table, "where" => $where, "order" => "time desc"));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $obj = new performanceScoreClass();
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate       = array(
                "box"    => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'sales_contract':
                        $sales_contract = query("sales_contract", " id = '" . $array['contractId'] . "' ");
                        $row[] = $sales_contract['name'];
                        break;
                    case 'companyName':
                        $kehu           = query("kehu", " khid = '" . $array['khid'] . "' ", 'companyName');
                        $row[] = $kehu['companyName'];
                        break;
                    case 'manager':
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case 'weight':
                        $total          = $this->calculatedWeight($array['id']);
                        $row[] = $total['weight'];
                        break;
                    case 'num':
                        $cars           = find(array("table" => "sale_send_order_car", "single" => " orderId = '$array[id]' and state = 1 ", "field" => " IFNULL(count(id),0) as num "));
                        $row[] = $cars['num'];
                        break;
                    case 'time':
                        $row[] = date('Y-m-d', strtotime($array['time']));
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx." as mx join material as mat on mx.materialId = mat.id",
            'single' => "mx.orderId in (select id from ".self::table." where 1=1 {$where})",
            'field'  => "ifnull(round(sum(mat.weight*mx.num),2)/1000,0) as weight",
        ]);
        $cars           = find(array("table" => "sale_send_order_car", "single" => " orderId in (select id from ".self::table." where 1=1 {$where}) and state = 1 ", "field" => " IFNULL(count(id),0) as num "));
        $total    = [
            'weight'        => self::lostZero($totalQuery['weight'],'numPrecision'),
            'num'        => $cars['num'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**计算发货重量和体积
     * @param $id $mode对应的id
     * @param $mode 1发货单  2发货单物料明细
     * @return array
     */
    public function calculatedWeight($id, $mode = 1): array
    {
        $json['weight'] = 0; //重量
        $json['volume'] = 0; //体积
        $json['num']    = 0; //数量
        $array          = [];
        if ($mode == 1) {
            $arr   = find(array("table" => self::tableMx, "where" => " orderId = '$id' ", "field" => "materialId,num"));
            $array = $arr['array'];
        } else {
            $array[] = find(array("table" => self::tableMx, "single" => " id = '$id' ", "field" => "materialId,num"));
        }
        foreach ((array)$array as $val) {
            $material       = query("material", " id = '$val[materialId]' ");
            $json['num']    += $val['num'];
            $json['weight'] += round((float)$material['weight'] * (float)$val['num'], 2) / 1000;
            $json['volume'] += round((float)$material['length'] * (float)$material['width'] * (float)$material['height'] * (float)$val['num'], 2) / 1000000;
        }
        return $json;
    }

    /*客户管理-客户详情页*/
    public function detail()
    {
        $info        = query(self::table, "id = '" . $this->get('id') . "'");
        $send_car_id = $this->get('send_car_id'); //当前操作的车辆ID
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            //按钮
            $button = [];
            if ($this->power(self::page, "edit") && $info['send_state'] > 0) {
                //按钮
                $button[] = [
                    "name" => "退回上一步",
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'back', "id" => $info['id']],
                ];
            }
            if ($info['send_state'] == 2) {
                $button[] = [
                    "name" => "回单登记",
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "receipt",
                    "post" => ["id" => $info['id']],
                ];
            }
            //发货明细
            $sales_contract = query('sales_contract', "id = '$info[contractId]'");
            $kehu           = query('kehu', "khid = '$info[khid]'");
            $total_tr = [];
            if ($info['send_state'] == 0) {
                $tr[]        = ['产品编码', '产品名称', '规格型号', '仓库', '主单位', '主单位数量', '重量（吨）', '体积（㎡）', '关联销售订单'];
                $totalNum    = 0;
                $totalWeight = 0;
                $totalVolume = 0;
                $result      = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
                foreach ($result['array'] as $array) {
                    $material     = query('material', " id = '$array[materialId]'");
                    $saleOrderMx  = query("sale_order_detail", "id = '$array[saleOrderMxId]'");
                    $saleOrder    = query('sale_order', "id = '$saleOrderMx[orderId]'");
                    $array['num'] = machiningOrderClass::material_num_change($material['id'], $array['unit'], $material['unit'], $array['num']);
                    $weight       = round((float)$material['weight'] * (float)$array['num'], 2) / 1000;
                    $volume       = round((float)$material['length'] * (float)$material['width'] * (float)$material['height'] * (float)$array['num'], 2) / 1000000;
                    $tr[]         = [
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        warehouseClass::getName($array['warehouseId']),
                        $material['unit'],
                        self::lostZero($array['num'], 'numPrecision'),
                        $weight,
                        $volume,
                        $saleOrder['orderNo'],
                    ];
                    $totalNum     += $array['num'];
                    $totalWeight  += $weight;
                    $totalVolume  += $volume;
                }
                $total_tr = [
                        5=>self::lostZero($totalNum, 'numPrecision'),
                        6=>self::lostZero($totalWeight, 'numPrecision'),
                        7=>self::lostZero($totalVolume, 'numPrecision')
                ];
            } else {
                $tr[]        = ['产品编码', '产品名称', '规格型号', '仓库', '主单位', '主单位数量', ($info['send_state'] == 1 ? '已发/未发' : '计划/实发'), '未发重量（吨）', '未发体积（㎡）', '关联销售订单'];
                $result      = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
                foreach ($result['array'] as $array) {
                    $material     = query('material', " id = '$array[materialId]'");
                    $saleOrderMx  = query("sale_order_detail", "id = '$array[saleOrderMxId]'");
                    $saleOrder    = query('sale_order', "id = '$saleOrderMx[orderId]'");
                    $array['num'] = machiningOrderClass::material_num_change($material['id'], $array['unit'], $material['unit'], $array['num']);
                    $singleVolume = (float)$material['length'] * (float)$material['width'] * (float)$material['height'] / 1000000; //单个物料体积
                    $weight       = round((float)$material['weight'] * (float)$array['num'], 2) / 1000;
                    $volume       = round($singleVolume * (float)$array['num'], 2);

                    $yetSend     = find(array("table" => "sale_send_order_loading", "single" => " orderId = '" . $info['id'] . "' and saleSendMxId = '" . $array['id'] . "' ", "field" => " IFNULL(sum(actual_num),0) as total "));  //已发数量
                    $yetWeight   = round((float)$material['weight'] * (float)$yetSend['total'], 2) / 1000;
                    $yetVolume   = round($singleVolume * (float)$yetSend['total'], 2);
                    $tr[]        = [
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        warehouseClass::getName($array['warehouseId']),
                        $material['unit'],
                        self::lostZero($array['num'], 'numPrecision'),
                        ($info['send_state'] == 1 ?
                            "<span class='green'>" . self::lostZero($yetSend['total'], 'numPrecision') . "</span> / <span class='red'>" . ((float)$array['num'] - $yetSend['total']) . "</span>" :
                            "<span class='green'>" . self::lostZero($array['num'], 'numPrecision') . "</span> / <span class='red'>" . self::lostZero($yetSend['total'], 'numPrecision') . "</span>"),
                        ($weight - $yetWeight),
                        ($volume - $yetVolume),
                        $saleOrder['orderNo'],
                    ];
                }
            }

            $receiptText = [];  //回单信息文本
            $receiptFile = [];  //回单附件
            //车辆信息
            $carBut     = ''; //车辆切换按钮
            $carInfo    = ''; //车辆信息
            $mxButton   = "
            <span class='smallButton' onclick=\"layer('" . self::page . "','addMx',{id:'" . $info['id'] . "'})\">选择内部车辆</span>
<span class='smallButton' onclick=\"layer('" . self::page . "','addMxExternal',{id:'" . $info['id'] . "'})\">选择外部车辆</span>
<span class='smallButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',act:'sendCar'})\">派车</span>
<span class='smallButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',act:'delMx'})\">移除</span>";
            $checkAll   = $this->checkAll("detailForm", "mxId");
            $tr2        = array([$checkAll, '类型', '车牌号', '规格型号', '核载（吨）', '驾驶员', '联系电话', '身份证号', '装货时间', '运费', '状态', '备注']);
            $title      = "装载明细";
            $detailhtml = ""; //车辆/车辆明细
            //待派车状态下的车辆明细
            if ($info['send_state'] == 0) {
                $title    = "车辆明细";
                $result   = find(array('table' => 'sale_send_order_car', 'where' => "orderId = '$info[id]' order by list asc"));
                $stateArr = [0 => '未派车', 1 => '已派车', 2 => '已发货'];
                foreach ($result['array'] as $val) {
                    //列表控件
                    $dominate = array(
                        "box" => array("name" => "mxId", "value" => $val['id']),
                    );
                    $tr2[]    = [
                        $this->dominate($dominate),
                        ($val['type'] == 0 ? '内部' : '外部'),
                        $val['car_no'],
                        $val['model'],
                        $val['maxWeight'],
                        $val['driver'],
                        $val['contactTel'],
                        $val['idCard'],
                        text([
                            'name' => 'loading_time',
                            'class' => 'text',
                            'value' => $val['loading_time'],
                            'laydate' => ['type' => 'datetime', 'done' => "function(value, date, endDate){updateLoadingTime('loading_time','{$this->get('cla')}','updateMx',{orderid:'{$info['id']}',id:'{$val['id']}',loading_time:value})}"],
                            'title' => '请选择'
                        ]),
                        text([
                            'name' => 'freight',
                            'data' => ['id' => $val['id'], 'orderId' => $info['id']],
                            'other' => self::digitalFiltering(),
                            'class' => 'text textPrice',
                            'value' => self::lostZero($val['freight']),
                            'blur' => "textUpdateNotRefresh, {$this->get('cla')}, updateMx",
                            'title' => '请填写'
                        ]),
                        $stateArr[$val['state']],
                        text([
                            'name' => 'text',
                            'data' => ['id' => $val['id'], 'orderId' => $info['id']],
                            'class' => 'text',
                            'value' => $val['text'],
                            'blur' => "textUpdateNotRefresh, {$this->get('cla')}, updateMx",
                            'title' => '备注'
                        ])];
                }
                $detailhtml = $this->editList([
                    'title' => $title,
                    'button' => $mxButton,
                    'html' => "
                    <div class='purchaseMx'>
                        <form name='detailForm'>" .
                        hidden(array('name' => 'id', 'value' => $info['id'])) .
                        $this->listTable(array('tr' => $tr2)) .
                        "</form>
                    </div>
                    ",
                ]);
            } else {

                $result      = find(array('table' => 'sale_send_order_car', 'where' => "orderId = '$info[id]' and state > 0 order by list asc"));
                $sale_send_order      = query('sale_send_order',"orderNo = '$info[orderNo]'");
                $stateArr    = [1 => '待发', 2 => '已发'];
                $send_car_id = $send_car_id ?: $result['array'][0]['id'];
                $carBut      .= "<div class='car-div'>";
                foreach ($result['array'] as $kk => $val) {
                    $carState = $info['send_state'] == 1 ? "-{$stateArr[$val['state']]}" : '';  //已派车状态下显示 车辆发货状态
                    if ($val['id'] == $send_car_id) {
                        $now     = "car-but-now";
                        $infoNow = '';
                    } else {
                        $now     = '';
                        $infoNow = 'hide';
                    }
                    $carBut   .= "<p class='car-but {$now}' onclick=\"switchCar(this,'{$val['id']}')\">{$val['car_no']}$carState</p>";
                    $mxButton = "";
                    $setBut   = "";
                    if ($val['driver'] != $info['delivery_manage'] && $info['send_state'] == 1) {
                        $setBut = "<span class='smallButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',send_car_id:'" . $val['id'] . "',act:'leader'})\">设为负责人</span>";
                    }
                    if ($val['state'] == 1) {
                        $setBut .= "<span class='smallButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',send_car_id:'" . $val['id'] . "',act:'carSend'})\">发货</span>";
                    }
                    $carInfo .= "<div carInfo='{$val['id']}' class='{$infoNow}'>" . $this->edit4(array(
                            array(
                                array(
                                    "<div class='flex-box'>".$val['orderNo'].$setBut."</div>",
                                ),
                                array(
                                    "车牌号："   => "[" . ($val['type'] == 0 ? '内' : '外') . "]{$val['car_no']}",
                                    "规格型号："  => $val['model'],
                                    "核载（吨）：" => $val['maxWeight'],
                                    "驾驶员："  => self::findStaff($sale_send_order['delivery_name']),
                                ),
                                array(
                                    "押运员："  => self::findStaff($sale_send_order['delivery_manage']),
                                    "联系电话：" => $val['contactTel'],
                                    "身份证号：" => $val['idCard'],
//                                    "负责人："    => $val['driver'] == $info['delivery_manage'] ? '是' : '否',
                                ),
                                array(
                                    "实际装货时间：" => $info['send_state'] == 1 && $val['state'] == 1 ?
                                        text([
                                            'name' => 'actual_loading_time',
                                            'class' => 'text',
                                            'value' => $val['actual_loading_time'],
                                            'laydate' => ['type' => 'datetime', 'done' => "function(value, date, endDate){updateLoadingTime('actual_loading_time','{$this->get('cla')}','updateMx',{orderid:'{$info['id']}',id:'{$val['id']}',actual_loading_time:value})}"],
                                            'title' => '请选择'
                                        ]) :
                                        $val['actual_loading_time'],
                                    "实际装货吨数：" => $info['send_state'] == 1 && $val['state'] == 1 ?
                                        text([
                                            'name' => 'actual_weight',
                                            'data' => ['id' => $val['id'], 'orderId' => $info['id']],
                                            'class' => 'text',
                                            'value' => $val['actual_weight'],
                                            'blur' => "textUpdateNotRefresh, {$this->get('cla')}, updateMx",
                                            'title' => '请填写'
                                        ]) :
                                        $val['actual_weight'],
                                    "运费（元）：" => self::lostZero($val['freight']),
                                ),
                                array(
                                    "备注："    => pre($val['text']),
                                ),
                            )
                        )) . "</div>";
                    //装在明细
                    if ($info['send_state'] == 1 && $val['state'] == 1) {
                        $mxButton = "
                        <span class='smallButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',send_car_id:'" . $val['id'] . "',act:'reset'})\">重置明细</span>
                        <span class='smallButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',send_car_id:'" . $val['id'] . "',act:'delLoading'})\">移除</span>
                        ";
                    }
                    $result = find(array('table' => 'sale_send_order_loading', 'where' => "orderId = '$info[id]' and send_car_id = '$val[id]' order by list asc"));
                    $tr2    = array([$checkAll, '产品编码', '产品名称', '规格型号', '仓库', '主单位', '主单位实发数量', '分摊运费', '重量（吨）', '体积（㎡）', '关联销售订单']);
                    foreach ($result['array'] as $array) {
                        //列表控件
                        $dominate    = array(
                            "box" => array("name" => "mxId", "value" => $array['id']),
                        );
                        $material    = query('material', " id = '$array[materialId]'");
                        $saleOrderMx = query("sale_order_detail", "id = '$array[saleOrderMxId]'");
                        $saleOrder   = query('sale_order', "id = '$saleOrderMx[orderId]'");
                        $weight      = round((float)$material['weight'] * (float)$array['actual_num'], 2) / 1000;
                        $volume      = round((float)$material['length'] * (float)$material['width'] * (float)$material['height'] * (float)$array['actual_num'], 2) / 1000000;
                        $tr2[]       = [
                            $this->dominate($dominate),
                            $material['code'],
                            $material['name'],
                            $material['model'],
                            warehouseClass::getName($array['warehouseId']),
                            $material['unit'],
                            $info['send_state'] == 1 && $val['state'] == 1 ?
                                text([
                                    'name' => 'actual_num',
                                    'data' => ['id' => $array['id'], 'orderId' => $info['id']],
                                    'class' => 'text textPrice',
                                    'value' => $array['actual_num'],
                                    'blur' => "textUpdateNotRefresh, {$this->get('cla')}, updateLoadingMx",
                                    'title' => '请填写'
                                ]) :
                                self::lostZero($array['actual_num'], 'numPrecision'),
                            $info['send_state'] == 1 && $val['state'] == 1 ?
                                text([
                                    'name' => 'freight',
                                    'data' => ['id' => $array['id'], 'orderId' => $info['id']],
                                    'class' => 'text',
                                    'other' => self::digitalFiltering(),
                                    'value' => self::lostZero($array['freight']),
                                    'blur' => "textUpdateNotRefresh, {$this->get('cla')}, updateLoadingMx",
                                    'title' => '备注'
                                ]) :
                                $array['freight'],
                            $weight,
                            $volume,
                            $saleOrder['orderNo'],
                        ];
                    }
                    /*$detailhtml = $this->detailList([
                        'class' => $infoNow,
                        'other' => " carInfo='{$val['id']}' ",
                        'title' => $title,
                        'button' => $mxButton,
                        'html' => "
                            <div carInfo='{$val['id']}' class='purchaseMx {$infoNow}'>
                                <form name='detailForm'>" .
                                hidden(array('name' => 'id', 'value' => $info['id'])) .
                                $this->tableMany(array('tr' => $tr2)) .
                                "</form>
                            </div>
                        ",
                    ]);*/
                    $detailhtml .= $this->editList([
                        'class' => $infoNow,
                        'other' => " carInfo='{$val['id']}' ",
                        'title' => $title,
                        'button' => $mxButton,
                        'html' => "
                            <div carInfo='{$val['id']}' class='purchaseMx {$infoNow}'>
                                <form name='detailForm'>" .
                            hidden(array('name' => 'id', 'value' => $info['id'])) .
                            $this->listTable(array('tr' => $tr2)) .
                            "</form>
                            </div>
                        ",
                    ]);
                }
                $carBut .= "</div>";
                //已发货或已签收状态下
                if ($info['send_state'] > 1) {
                    $receiptText = array(
                        array(
                            "回单日期" => $info['receipt_date'],
                            "备注"   => $info['receipt_text'],
                        )
                    );
                    $receiptFile = array(
                        array(
                            fileUploadClass::showFile($info['id'], '回单凭证')
                        )
                    );
                }
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '详细信息'   => array(
                    array(
                        "客户"   => $kehu['companyName'],
                        "合同名称" => $sales_contract['name'],
                        "单据日期" => self::null($info['recordDate']),
                        "交货方式" => '配送',
                    ),
                    array(
                        "送货时限" => self::null($info['limitTime']),
                        "收货人"  => $info['contactName'],
                        "收货电话" => $info['contactTel'],
                        "收货地址" => $info['address'],
                    ),
                    array(
                        "单据编号" => $info['orderNo'],
                        "制单人"  => self::findStaff($info['stid']),
                        //"状态" => $info['state'],//self::operateLog($info['id'])
                    ),
                    array(
                        "备注"   => pre($info['text']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '发货明细',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailBlock([
                '附件' => fileUploadClass::showFile($info['id'], '销售发货单')
            ]);
            if ($carInfo) {
                $data['html'] .= $this->detailList([
                    'title' => '装载数据',
                    'html' => $carBut . $carInfo,
                ]);
            }
            $data['html'] .= $detailhtml;
            $data['html'] .= $this->tableShow(array(
                $receiptText,
                $receiptFile,
            ));
            //生成页面
            $html = $this->tab($data);
        }
        $html .= <<<efo
<style>
    .car-div{
        display: flex;
        justify-content: flex-start;
    }
    .car-but{
        background-color: #ebeaea;
        padding: 10px;
        margin-right: 10px;
        color: black;
        cursor: pointer;
    }
    .car-but-now{
        background-color: #6aacfb!important;
        color: #f8f8f8!important;
    }
</style>
<script>
    function updateLoadingTime(name,cla,fun,params){
        const url = root + 'control/adIndex.html?cla=' + cla + '&fun=' + fun
        $.post(url, params, function (resp) {
            if (resp.warn == 2) {
                $("[name='"+name+"']").css('background-color','#fdc1c1')
            } else {
                warn(resp.warn)
            }
        }, "json");
    }
    function switchCar(obj,id) {
      $(".car-but").removeClass('car-but-now');
      $(obj).addClass('car-but-now');
      $("[carInfo]").addClass('hide');
      $("[carInfo='" + id + "']").removeClass("hide");
    }
    // 单个文本框更新，不刷新页面
    function textUpdateNotRefresh(obj, cla, fun) {
        let field = $(obj).attr('name'), val = $(obj).val()
        if (field.length > 0) {
            const url = root + 'control/adIndex.html?cla=' + cla + '&fun=' + fun
            let params = {}
            // 判断是否有data-* 参数
            if ($(obj).data()) {
                Object.assign(params, $(obj).data())
                params[field] = val
            }
            $.post(url, params, function (resp) {
                if (resp.warn == 2) {
                    $(obj).css('background-color','#fdc1c1')
                } else {
                    warn(resp.warn)
                }
            }, "json");
        }
    }
</script>
efo;
        //返回
        return $html;
    }

    /**
     * 添加内部车辆
     * @return bool|string
     */
    public function addMx()
    {
        $html   =
            text(array("name" => "car_no", "title" => "车牌号")) .
            text(array("name" => "model", "title" => "规格型号")) .
            text(array("name" => "driver", "title" => "驾驶员")) .
            hidden(array('name' => 'id', 'value' => $this->post('id')));
        $button = "<input style='margin-left: 5px' onclick=\"subForm('mxForm', '" . root . "control/adIndex.html?cla=" . self::page . "&fun=addMxEdit');\" type='button' class='searchSub' value='提交'>";
        $html   = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button));
    }

    /**
     *添加明细
     */
    public function addMxSearch()
    {
        $id = $this->post('id');
        //$info = query(self::table, " id = '$id'");
        $where = " 1=1 and id not in (select car_id from sale_send_order_car where orderId = '{$id}')";
        $and   = '';
        $like  = [
            'model' => $this->post('model'),
        ];
        $equal = [
            'coid'  => self::$coid,
            'state' => '正常',
        ];
        if ($this->post('car_no')) {
            $and .= " and concat(shortName,carNo) like '%" . $this->post('car_no') . "%' ";
        }
        if ($this->post('driver')) {
            $and .= " and driverId in (select id from logistics_driver where name like '%" . $this->post('driver') . "%') ";
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page  = $this->page([
            "table"   => "logistics_car",
            "where"   => " {$where} ",
            'pageNum' => 50,
            "order"   => " `time` ASC",
        ]);
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[]     = [$checkAll, '类型', '车牌号', '规格型号', '驾驶员'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['id']),
            );
            $driver   = query('logistics_driver', "id = '$array[driverId]'");
            $tr[]     = array(
                $this->dominate($dominate),
                '内部',
                $array['shortName'] . $array['carNo'],
                $array['model'],
                $driver['name'],
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . hidden(array('name' => 'id', 'value' => $id)) . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     * 添加
     * @return bool|string
     */
    public function addMxEdit()
    {
        $id      = $this->post('id');
        $mxIdArr = $this->post('mxId');
        $info    = query(self::table, " id = '{$this->post('id')}'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择内部车辆';
        } else {
            $x = 0;
            foreach ($mxIdArr as $mxId) {
                $logistics_car = query('logistics_car', " id = '$mxId'");
                $mx            = query('sale_send_order_car', " car_id = '$mxId' and orderId = '$id'");
                $driver        = query('logistics_driver', "id = '$logistics_car[driverId]'");
                if (!$mx['id']) {
                    $userNo = codeTemplateClass::generateCode(self::page, [
                        'prefix'  => 'DJYD' . date('Ymd'),
                        'table'   => 'sale_send_order_car',
                        'field'   => 'orderNo',
                        'default' => '000001',
                        'where'   => '',
                    ], []);
                    //未在明细中
                    $warn = insert(array(
                        'table' => 'sale_send_order_car',
                        'field' => [
                            'id'         => suiji(),
                            'coid'       => self::$coid,
                            'orderId'    => $id,
                            'type'       => 0,
                            'car_id'     => $mxId,
                            'car_no'     => $logistics_car['shortName'] . $logistics_car['carNo'],
                            'model'      => $logistics_car['model'],
                            'maxWeight'  => $logistics_car['maxWeight'],
                            'driver'     => $driver['name'],
                            'contactTel' => $driver['contactTel'],
                            'idCard'     => $driver['idCard'],
                            'orderNo'    => $userNo,
                            'time'       => $this->time
                        ]
                    ));
                    if ($warn == '新增成功') {
                        $x++;
                        $text = $this->control['name'] . "添加了内部车辆信息【{$logistics_car['shortName']}{$logistics_car['carNo']}】到发货管理【{$info['orderNo']}】中";
                        $this->logText(array("type" => self::page, "text" => $text));
                    }
                }
            }
            $json['warn']     = 2;
            $_SESSION['warn'] = '添加了' . $x . '条车辆到发货管理中';
        }
        return json_encode($json, 320);
    }

    /**
     * 添加外部车辆
     * @return bool|string
     */
    public function addMxExternal()
    {
        $html   =
            text(array("name" => "car_no", "title" => "车牌号")) .
            text(array("name" => "model", "title" => "规格型号")) .
            text(array("name" => "driver", "title" => "驾驶员")) .
            hidden(array('name' => 'id', 'value' => $this->post('id')));
        $button = "<input onclick=\"subForm('mxForm', '" . root . "control/adIndex.html?cla=" . self::page . "&fun=addMxExternalEdit');\" type='button' class='searchSub m-l-5' value='提交'>";
        $url    = root . "control/adIndex.html?cla=logisticsTransferCar";
        $button .= "<input style='margin-left: 8px;border: 1px solid rgb(194, 219, 255);background-color: rgb(255, 255, 255) !important;color: rgba(123, 77, 18, 0.698) !important;' onclick=\"newIframe('外调车辆详情','" . $url . "&fun=edit');\" type='button' class='searchSub' value='添加外部车辆'>";
        $html   = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button));
    }

    /**
     *添加明细
     */
    public function addMxExternalSearch()
    {
        $id = $this->post('id');
        //$info = query(self::table, " id = '$id'");
        $where = " 1=1 and id not in (select car_id from sale_send_order_car where orderId = '{$id}')";
        $and   = '';
        $like  = [
            'model' => $this->post('model'),
            'name'  => $this->post('driver'),
        ];
        $equal = [
            'coid' => self::$coid,
        ];
        if ($this->post('car_no')) {
            $and .= " and concat(shortName,carNo) like '%" . $this->post('car_no') . "%' ";
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page  = $this->page([
            "table"   => "logistics_transfer_car",
            "where"   => " {$where} ",
            'pageNum' => 50,
            "order"   => " `time` ASC",
        ]);
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[]     = [$checkAll, '类型', '车牌号', '规格型号', '驾驶员'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['id']),
            );
            $tr[]     = array(
                $this->dominate($dominate),
                '外部',
                $array['shortName'] . $array['carNo'],
                $array['model'],
                $array['name'],
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . hidden(array('name' => 'id', 'value' => $id)) . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     * 添加
     * @return bool|string
     */
    public function addMxExternalEdit()
    {
        $id      = $this->post('id');
        $mxIdArr = $this->post('mxId');
        $info    = query(self::table, " id = '{$this->post('id')}'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择外部车辆';
        } else {
            $x = 0;
            foreach ($mxIdArr as $mxId) {
                $logistics_transfer_car = query('logistics_transfer_car', " id = '$mxId'");
                $mx                     = query('sale_send_order_car', " car_id = '$mxId' and orderId = '$id'");
                if (!$mx['id']) {
                    $userNo = codeTemplateClass::generateCode(self::page, [
                        'prefix'  => 'DJYD' . date('Ymd'),
                        'table'   => 'sale_send_order_car',
                        'field'   => 'orderNo',
                        'default' => '000001',
                        'where'   => '',
                    ], []);
                    //未在明细中
                    $warn = insert(array(
                        'table' => 'sale_send_order_car',
                        'field' => [
                            'id'         => suiji(),
                            'coid'       => self::$coid,
                            'orderId'    => $id,
                            'type'       => 1,
                            'car_id'     => $mxId,
                            'car_no'     => $logistics_transfer_car['shortName'] . $logistics_transfer_car['carNo'],
                            'model'      => $logistics_transfer_car['model'],
                            'maxWeight'  => $logistics_transfer_car['maxWeight'],
                            'driver'     => $logistics_transfer_car['name'],
                            'contactTel' => $logistics_transfer_car['contactTel'],
                            'idCard'     => $logistics_transfer_car['idCard'],
                            'orderNo'    => $userNo,
                            'time'       => $this->time
                        ]
                    ));
                    if ($warn == '新增成功') {
                        $x++;
                        $text = $this->control['name'] . "添加了外部车辆信息【{$logistics_transfer_car['shortName']}{$logistics_transfer_car['carNo']}】到发货管理【{$info['orderNo']}】中";
                        $this->logText(array("type" => self::page, "text" => $text));
                    }
                }
            }
            $json['warn']     = 2;
            $_SESSION['warn'] = '添加了' . $x . '条车辆到发货管理中';
        }
        return json_encode($json, 320);
    }

    //更新派车明细
    public function updateMx()
    {
        // 条件字段
        $wField = [
            'id'      => $this->post('id'),
            'orderId' => $this->post('orderid'),
        ];
        $field  = [];
        // 更新字段
        if ($this->post('loading_time') !== null) $field['loading_time'] = $this->post('loading_time');
        if ($this->post('freight') !== null) $field['freight'] = $this->post('freight') ? self::formattingFigure($this->post('freight')) : 0;
        if ($this->post('text') !== null) $field['text'] = $this->post('text');
        if ($this->post('actual_loading_time') !== null) $field['actual_loading_time'] = $this->post('actual_loading_time');
        if ($this->post('actual_weight') !== null) $field['actual_weight'] = $this->post('actual_weight');
        $info = query(self::table, " id = '{$wField['orderId']}' ");
        if (!in_array($info['send_state'], [0, 1])) {
            $json['warn'] = self::title . '发货单非待派车或已派车状态，无法修改';
        } else {
            $where        = generateWhere($wField);
            $warn         = update([
                'table' => 'sale_send_order_car',
                'field' => $field,
                'where' => $where,
            ]);
            $json['warn'] = ($warn == '更新成功') ? 2 : $warn;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&send_car_id=" . $this->post('id') . "&id=" . $this->post('orderid');
        }
        return json_encode($json, 320);
    }

    //更新装载明细
    public function updateLoadingMx()
    {
        // 条件字段
        $wField = [
            'id'      => $this->post('id'),
            'orderId' => $this->post('orderid'),
        ];
        // 更新字段
        $field = [
            'actual_num' => $this->post('actual_num'),
            'freight'    => $this->post('freight'),
        ];
        $info  = query(self::table, " id = '{$wField['orderId']}' ");
        if ($info['send_state'] != 1) {
            $json['warn'] = self::title . '发货单非已派车状态，无法修改';
        } else {
            $where                   = generateWhere($wField);
            $sale_send_order_loading = query("sale_send_order_loading", $where);
            $warn                    = static::update([
                'table' => 'sale_send_order_loading',
                'field' => $field,
                'where' => $where,
            ], false);
            $json['warn']            = ($warn == '更新成功') ? 2 : $warn;
            if ($json['warn'] == 2) $_SESSION['warn'] = $this->deliveringAmount($sale_send_order_loading);
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&send_car_id=" . $sale_send_order_loading['send_car_id'] . "&id=" . $this->post('orderid');
        }
        return json_encode($json, 320);
    }

    // 发货量查询
    public function deliveringAmount($sale_send_order_loading)
    {
        $sale_send_order_detail = query(self::tableMx, " id = '" . $sale_send_order_loading['saleSendMxId'] . "' ");
        $material               = query('material', " id = '$sale_send_order_detail[materialId]'");
        $yetSend                = find(array(
            "table" => "sale_send_order_loading",
            "single" => " orderId = '" . $sale_send_order_detail['orderId'] . "' and saleSendMxId = '" . $sale_send_order_detail['id'] . "' ",
            "field" => " IFNULL(sum(actual_num),0) as total "
        ));
        return $yetSend['total'] > $sale_send_order_detail['num'] ?
            $material['name'] . "的总实发数量【" . self::lostZero($yetSend['total'], 'numPrecision') . "】已超过订单数据【" . self::lostZero($sale_send_order_detail['num'], 'numPrecision') . "】"
            : '';
    }

    // 操作中转
    public function operate()
    {
        $act    = $this->post('act') ?? '';
        $pwd    = $word = false; // 需要密码
        $form   = $power = '';
        $page = self::page;
        $append = [];
        switch ($act) {
            case 'sendCar':
                $act      = 'edit';
                $msg      = '发货派车';
                $title    = '您正在对选中的车辆派车，是否确认要这样做？';
                $function = 'sendCar';
                $form     = self::page . 'OperateForm, detailForm';
                $word     = true;
                break;
            case 'delMx':
                $act      = 'del';
                $msg      = self::title . '删除车辆信息';
                $title    = '是否确认删除选中的车辆信息？';
                $function = 'delMx';
                $form     = self::page . 'OperateForm, detailForm';
                $word     = true;
                break;
            case 'shipping':
                $page = 'deliveryManageAlready';
                $act      = 'edit';
                $msg      = '发运';
                $title    = '是否确认发运选中的发货单？';
                $function = 'shipping';
                $form     = self::page . 'OperateForm, listForm';
                $word     = true;
                break;
            case 'back':
                $act      = 'edit';
                $msg      = '退回上一步';
                $title    = '是否确认退回上一步？';
                $function = 'back';
                $form     = self::page . 'OperateForm, detailForm';
                $word     = true;
                break;
            case 'reset':
                $act      = 'edit';
                $msg      = '重置明细';
                $title    = '是否确认重置车载明细？';
                $function = 'reset';
                $form     = self::page . 'OperateForm, detailForm';
                $word     = true;
                $append   = [hidden(array("name" => "send_car_id", "value" => $this->post('send_car_id')))];
                break;
            case 'leader':
                $act      = 'edit';
                $msg      = '设置负责人';
                $title    = '是否确认设置该车辆驾驶员为负责人？';
                $function = 'leader';
                $form     = self::page . 'OperateForm, detailForm';
                $word     = true;
                $append   = [hidden(array("name" => "send_car_id", "value" => $this->post('send_car_id')))];
                break;
            case 'carSend':
                $act      = 'edit';
                $msg      = '发货';
                $title    = '是否确认该车辆为发货？';
                $function = 'carSend';
                $form     = self::page . 'OperateForm, detailForm';
                $word     = true;
                $append   = [hidden(array("name" => "send_car_id", "value" => $this->post('send_car_id')))];
                break;
            case 'delLoading':
                $act      = 'edit';
                $msg      = '删除车载明细';
                $title    = '是否确认移除车载明细？';
                $function = 'delLoading';
                $form     = self::page . 'OperateForm, detailForm';
                $word     = true;
                $append   = [hidden(array("name" => "send_car_id", "value" => $this->post('send_car_id')))];
                break;
            /*default:
                $act      = 'del';
                $msg      = '删除' . self::title;
                $title    = self::page . 'Delete';
                $function = 'isDelete';
                $form     = self::page . 'OperateForm, listForm';
                break;*/
        }
        if (!$this->power($page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'append'   => $append,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    //设置负责人
    public function leader()
    {
        $send_car_id = $this->post('send_car_id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有设置负责人权限";
        } elseif (empty($send_car_id)) {
            $json['warn'] = "派车信息为空";
        } else {
            // 判断field
            $fieldKey            = 'send_state';
            $fieldVlaue          = 1;
            $sale_send_order_car = query("sale_send_order_car", " id = '$send_car_id' ");
            $sale_send_order     = query(self::table, " id = '$sale_send_order_car[orderId]' ");
            if ((int)$sale_send_order[$fieldKey] !== $fieldVlaue) {
                $json['warn'] = self::title . "【{$sale_send_order['orderNo']}】非已派车状态，无法删除<br>";
            } else {
                update(array(
                    "table" => self::table,
                    "field" => ['delivery_manage' => $sale_send_order_car['driver']],
                    "where" => "id = '$sale_send_order[id]'",
                ));
                $_SESSION['warn'] = "设置成功";
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&send_car_id=" . $send_car_id . "&id=" . $sale_send_order_car['orderId'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    //车辆发货
    public function carSend()
    {
        $send_car_id = $this->post('send_car_id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有操作发货的权限";
        } elseif (empty($send_car_id)) {
            $json['warn'] = "派车信息为空";
        } else {
            // 判断field
            $fieldKey            = 'state';
            $fieldVlaue          = 1;
            $sale_send_order_car = query("sale_send_order_car", " id = '$send_car_id' ");
            if ((int)$sale_send_order_car[$fieldKey] !== $fieldVlaue) {
                $json['warn'] = "车辆【{$sale_send_order_car['car_no']}】非已派车状态，无法发货<br>";
            } else {
                update(array(
                    "table" => 'sale_send_order_car',
                    "field" => ['state' => 2],
                    "where" => "id = '$sale_send_order_car[id]'",
                ));
                $_SESSION['warn'] = "发货成功";
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&send_car_id=" . $send_car_id . "&id=" . $sale_send_order_car['orderId'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 确认车载删除明细
    public function delLoading()
    {
        $send_car_id = $this->post('send_car_id');
        $array       = $this->post('mxId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有移除车载明细的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            $fieldKey            = 'send_state';
            $fieldVlaue          = 1;
            $sale_send_order_car = query("sale_send_order_car", " id = '$send_car_id' ");
            $sale_send_order     = query(self::table, " id = '$sale_send_order_car[orderId]' ");
            if ((int)$sale_send_order[$fieldKey] !== $fieldVlaue) {
                $json['warn'] = self::title . "【{$sale_send_order['orderNo']}】非已派车状态，无法删除<br>";
            } else {
                foreach ($array as $id) {
                    $where = " id = '$id' AND orderId = '$sale_send_order_car[orderId]' and send_car_id = '$sale_send_order_car[id]' ";
                    $info  = query('sale_send_order_loading', $where);
                    if ($info['id']) {
                        // 删除表
                        delete(["table" => 'sale_send_order_loading', "where" => $where]);
                        $x++;
                    }
                }
                $_SESSION['warn'] = "删除了{$x}条车载信息";
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&send_car_id=" . $send_car_id . "&id=" . $sale_send_order_car['orderId'];
            }
        }
        resp:
        return json_encode($json, 320);
    }


    //重置装载明细
    public function reset()
    {
        $send_car_id = $this->post('send_car_id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没重置" . self::title . "装载明细的权限";
        } elseif (empty($send_car_id)) {
            $json['warn'] = "派车信息为空";
        } else {
            // 判断field
            $fieldKey            = 'send_state';
            $fieldVlaue          = 1;
            $sale_send_order_car = query("sale_send_order_car", " id = '$send_car_id' ");
            $sale_send_order     = query(self::table, " id = '$sale_send_order_car[orderId]' ");
            if ((int)$sale_send_order[$fieldKey] !== $fieldVlaue) {
                $json['warn'] = self::title . "【{$sale_send_order['orderNo']}】非已派车状态，无法删除<br>";
            } else {
                delete(["table" => 'sale_send_order_loading', "where" => " orderId = '$sale_send_order_car[orderId]' and send_car_id = '$sale_send_order_car[id]' "]);
                //插入装载明细
                $result = find(array('table' => self::tableMx, 'where' => "orderId = '$sale_send_order[id]' order by list"));
                foreach ($result['array'] as $array) {
                    insert(array(
                        'table' => 'sale_send_order_loading',
                        'field' => [
                            'id'            => suiji(),
                            'coid'          => self::$coid,
                            'orderId'       => $sale_send_order['id'],
                            'saleOrderMxId' => $array['saleOrderMxId'],
                            'saleSendMxId'  => $array['id'],
                            'send_car_id'   => $sale_send_order_car['id'],
                            'materialId'    => $array['materialId'],
                            'warehouseId'   => $array['warehouseId'],
                            'num'           => $array['num'],
                            'time'          => $this->time
                        ]
                    ));
                }
                $_SESSION['warn'] = "重置成功";
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&send_car_id=" . $send_car_id . "&id=" . $sale_send_order_car['orderId'];
            }
        }
        resp:
        return json_encode($json, 320);
    }


    //派车
    public function sendCar()
    {
        $orderId = $this->post('id');
        $array   = $this->post('mxId');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没派车" . self::title . "的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            $fieldKey        = 'send_state';
            $fieldVlaue      = 0;
            $sale_send_order = query(self::table, " id = '$orderId' ");
            if ((int)$sale_send_order[$fieldKey] !== $fieldVlaue) {
                $json['warn'] = self::title . "【{$sale_send_order['orderNo']}】非待派车状态，无法删除<br>";
            } else {
                update(array(
                    "table" => self::table,
                    "field" => ['send_state' => 1],
                    "where" => "id = '$sale_send_order[id]'",
                ));
                foreach ($array as $id) {
                    $where = " id = '$id' AND orderId = '$orderId' ";
                    $info  = query('sale_send_order_car', $where);
                    if ($info['id'] && (int)$info['state'] == 0) {
                        // 修改派车状态
                        update(array(
                            "table" => 'sale_send_order_car',
                            "field" => ['state' => 1],
                            "where" => "id = '$info[id]'",
                        ));
                        //插入装载明细
                        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$sale_send_order[id]' order by list"));
                        foreach ($result['array'] as $array) {
                            $mx = query('sale_send_order_loading', " send_car_id = '$id' and orderId = '$orderId' and saleSendMxId = '$array[id]' ");
                            if (!$mx['id']) {
                                //未在明细中
                                insert(array(
                                    'table' => 'sale_send_order_loading',
                                    'field' => [
                                        'id'            => suiji(),
                                        'coid'          => self::$coid,
                                        'orderId'       => $orderId,
                                        'saleOrderMxId' => $array['saleOrderMxId'],
                                        'saleSendMxId'  => $array['id'],
                                        'send_car_id'   => $id,
                                        'materialId'    => $array['materialId'],
                                        'warehouseId'   => $array['warehouseId'],
                                        'num'           => $array['num'],
                                        'time'          => $this->time
                                    ]
                                ));
                            }
                        }
                        $x++;
                    }
                }
                $_SESSION['warn'] = "派车了{$x}条车辆信息";
                $json['warn']     = 2;
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 确认删除明细
    public function delMx()
    {
        $orderId = $this->post('id');
        $array   = $this->post('mxId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除" . self::title . "的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            $fieldKey        = 'send_state';
            $fieldVlaue      = 0;
            $sale_send_order = query(self::table, " id = '$orderId' ");
            if ((int)$sale_send_order[$fieldKey] !== $fieldVlaue) {
                $json['warn'] = self::title . "【{$sale_send_order['orderNo']}】非待派车状态，无法删除<br>";
            } else {
                foreach ($array as $id) {
                    $where = " id = '$id' AND orderId = '$orderId' ";
                    $info  = query('sale_send_order_car', $where);
                    if ($info['id']) {
                        // 删除表
                        delete(["table" => 'sale_send_order_car', "where" => $where]);
                        $x++;
                    }
                }
                $_SESSION['warn'] = "删除了{$x}条车辆信息";
                $json['warn']     = 2;
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 确认发运
    public function shipping()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power('deliveryManageAlready', "edit")) {
            $json['warn'] = "你没有编辑发运" . self::title . "的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $text  = '';
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            $fieldKey   = 'send_state';
            $fieldVlaue = 1;

            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info  = query(self::table, $where);
                if ($info['id']) {
                    if ((int)$info[$fieldKey] !== $fieldVlaue) {
                        $text .= self::title . "【{$info['id']}】非已派车状态，无法操作发运<br>";
                        continue;
                    }
                    update(array(
                        "table" => self::table,
                        "field" => ['send_state' => 2, 'send_date' => $this->date],
                        "where" => "id = '$info[id]'",
                    ));
                    //添加记录
                    $text .= "{$this->control['name']}操作发运了一条" . self::title . "：ID【{$id}】" . ($info['orderNo'] ? "，发货单号【{$info['orderNo']}】" : '') . '<br>';
                    $x++;
                }
            }

            // 写入日志
            $this->logText(["type" => 'deliveryManageAlready', "text" => $text]);
            $_SESSION['warn'] = "发运了{$x}条" . self::title;
            $json['warn']     = 2;
            //$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=already&id=all";
        }

        resp:
        return json_encode($json, 320);
    }

    // 退回上一步
    public function back()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $text  = '';
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            $fieldKey   = 'send_state';
            $fieldVlaue = 0;
            $stateArr   = ['待派车', '已派车', '已发货', '已签收'];
            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info  = query(self::table, $where);
                if ($info['id']) {
                    if ((int)$info[$fieldKey] == $fieldVlaue) {
                        $text .= self::title . "【{$info['id']}】已为最初始状态，请勿重复操作<br>";
                        continue;
                    }
                    update(array(
                        "table" => self::table,
                        "field" => ['send_state' => (int)$info[$fieldKey] - 1],
                        "where" => "id = '$info[id]'",
                    ));
                    update(array(
                        "table" => 'sale_send_order_car',
                        "field" => ['state' => (int)$info[$fieldKey] - 1],
                        "where" => "orderId = '$info[id]'",
                    ));
                    //添加记录
                    $text .= "{$this->control['name']}操作了一条" . self::title . "：ID【{$id}】" . ($info['orderNo'] ? "，发货单号【{$info['orderNo']}】" : '') . "退回上一步至【" . $stateArr[(int)$info[$fieldKey] - 1] . "】<br>";
                    $x++;
                }
            }

            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "退回成功";
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $this->post('id');
        }

        resp:
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function alreadyOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('已派车');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*发货列表-查询条件*/
    public function already(): string
    {
        $html = $this->alreadyOptions(false);
        //控件
        $button = "";
        if ($this->power('deliveryManageAlready', "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'shipping'})\">发运</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 已派车
     * @return bool|string
     */
    public function alreadySearch(): bool|string
    {
        //like查询数组
        $like = array(
            "orderNo"     => $this->post('orderNo'),
            "contactName" => $this->post('contactName'),
            "contactTel"  => $this->post('contactTel'),
            "address"     => $this->post('address'),
        );
        //全等查询数组
        $equal = array(
            'coid'       => self::$coid,
            'send_state' => 1,  //已派车
            "manager"    => $this->post('stid'),
        );

        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'));
        }
        if ($this->post('contractName')) {
            $and2 = '';
            if ($this->post('contractName')) {
                $and2 .= " and name like '%" . $this->post('contractName') . "%' ";
            }
            $and .= " and contractId in (select id from sales_contract where 1=1 {$and2}) ";
        }
        if ($this->post('carInfo')) {
            $and .= " and id in (select orderId from sale_send_order_car where car_no like '%" . $this->post('carInfo') . "%' or driver like '%" . $this->post('carInfo') . "%' or contactTel like '%" . $this->post('carInfo') . "%') ";
        }
        if ($this->post('unitA')) {
            $and .= " and khid in (select khid from kehu where companyName like '%" . $this->post('unitA') . "%') ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $obj = new performanceScoreClass();
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate       = array(
                "box"    => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            $total          = $this->calculatedWeight($array['id']);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'sales_contract':
                        $sales_contract = query("sales_contract", " id = '" . $array['contractId'] . "' ");
                        $row[] = $sales_contract['name'];
                        break;
                    case 'companyName':
                        $kehu           = query("kehu", " khid = '" . $array['khid'] . "' ", 'companyName');
                        $row[] = $kehu['companyName'];
                        break;
                    case 'carInfo':
                        $carInfo        = $this->carInfo($array['id']);
                        $row[] = $carInfo;
                        break;
                    case 'num':
                        $row[] = $total['num'];
                        break;
                    case 'weight':
                        $row[] = $total['weight'];
                        break;
                    case 'carsWeight':
                        $cars           = find(array("table" => "sale_send_order_car", "single" => " orderId = '$array[id]' ", "field" => " IFNULL(sum(maxWeight),0) as weight "));
                        $row[] = $cars['weight'];
                        break;
                    case 'time':
                        $row[] = date('Y-m-d', strtotime($array['time']));
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx." as mx join material as mat on mx.materialId = mat.id",
            'single' => "mx.orderId in (select id from ".self::table." where 1=1 {$where})",
            'field'  => "ifnull(round(sum(mat.weight*mx.num),2)/1000,0) as weight,ifnull(sum(mx.num),0) as num",
        ]);
        $cars           = find(array("table" => "sale_send_order_car", "single" => " orderId in (select id from ".self::table." where 1=1 {$where}) ", "field" => " IFNULL(sum(maxWeight),0) as weight "));
        $total    = [
            'num'        => self::lostZero($totalQuery['num'],'numPrecision'),
            'weight'        => self::lostZero($totalQuery['weight'],'numPrecision'),
            'carsWeight'        => $cars['weight'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**车辆信息
     * @param $id  发货单id
     * @return string
     */
    public function carInfo($id): string
    {
        $html   = '';
        $result = find(array("table" => "sale_send_order_car", "where" => " orderId = '$id' ", "field" => "type,car_no,driver,contactTel"));
        foreach ((array)$result['array'] as $array) {
            $html .= "[" . ($array['type'] == 0 ? '内' : '外') . "]{$array['car_no']}".
                ($array['driver']?'，'.$array['driver']:'').
                ($array['contactTel']?'，'.$array['contactTel']:'') .
                ";";
        }
        return $html;
    }

    /*列表页-查询条件*/
    public function deliveryOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('已发货');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*发货列表-查询条件*/
    public function delivery(): string
    {
        $html = $this->deliveryOptions(false);
        //控件
        $button = "";
        if ($this->power('deliveryManageDelivery', "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'receipt', {'id': ''})\">回单登记</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 已发货
     * @return bool|string
     */
    public function deliverySearch(): bool|string
    {
        //like查询数组
        $like = array(
            "orderNo"     => $this->post('orderNo'),
            "contactName" => $this->post('contactName'),
            "contactTel"  => $this->post('contactTel'),
            "address"     => $this->post('address'),
        );
        //全等查询数组
        $equal = array(
            'coid'       => self::$coid,
            'send_state' => 2,  //已发货
            "manager"    => $this->post('stid'),
        );

        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'));
        }
        if ($this->post('contractName')) {
            $and2 = " and name like '%" . $this->post('contractName') . "%' ";
            $and  .= " and contractId in (select id from sales_contract where 1=1 {$and2}) ";
        }
        if ($this->post('carInfo')) {
            $and .= " and id in (select orderId from sale_send_order_car where car_no like '%" . $this->post('carInfo') . "%' or driver like '%" . $this->post('carInfo') . "%' or contactTel like '%" . $this->post('carInfo') . "%') ";
        }
        if ($this->post('unitA')) {
            $and .= " and khid in (select khid from kehu where companyName like '%" . $this->post('unitA') . "%') ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $obj = new performanceScoreClass();
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate       = array(
                "box"    => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'sales_contract':
                        $sales_contract = query("sales_contract", " id = '" . $array['contractId'] . "' ");
                        $row[] = $sales_contract['name'];
                        break;
                    case 'companyName':
                        $kehu           = query("kehu", " khid = '" . $array['khid'] . "' ", 'companyName');
                        $row[] = $kehu['companyName'];
                        break;
                    case 'carInfo':
                        $carInfo        = $this->carInfo($array['id']);
                        $row[] = $carInfo;
                        break;
                    case 'total':
                        $total          = find(['table' => 'sale_send_order_car', 'sum' => 'actual_weight', 'single' => " orderId = '$array[id]' "]);
                        $row[] = $total;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $total    = [
            'total'        => self::lostZero(
                find(['table' => 'sale_send_order_car', 'sum' => 'actual_weight', 'single' => " orderId in (select id from ".self::table." where 1=1 {$where}) "]),
                'numPrecision'
            ),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 回单登记
     * @return bool|string
     */
    public function receipt(): bool|string
    {
        //生成表单
        $fileUpload = new fileUploadClass();
        $html       = $this->layerEdit(array("table" => array(
            array(
                must . "回单日期：" => text(array('name' => 'receipt_date', 'laydate' => [], 'value' => $this->date)),
            ),
            array(
                "备注：" => textarea(array('name' => 'receipt_text', 'class' => 'textarea')),
            ),
            array(
                '附件' => $fileUpload->addFileComponent('', '回单凭证', self::page, self::page . 'ReceiptForm'),
            )
        ), 'hidden'                                  => hidden(array('name' => 'id', 'value' => $this->post('id')))
        ));
        //返回
        return $this->layer(array("title" => "回单登记", "height" => 480, "width" => 900, "html" => $html, 'formTwo' => 'listForm'));
    }


    /**
     * 回单登记
     */
    public function receiptEdit(): bool|string
    {
        $array     = $this->post('listId') ?? $this->post('id');
        $fileIdArr = $this->post('fileId');
        if (!$this->power('deliveryManageDelivery', "edit")) {
            $json['warn'] = "你没有回单登记" . self::title . "的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } elseif (empty($this->post('receipt_date'))) {
            $json['warn'] = "请选择回单日期";
        } else {
            $text  = '';
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            $fieldKey   = 'send_state';
            $fieldVlaue = 2;
            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info  = query(self::table, $where);
                if ($info['id']) {
                    if ((int)$info[$fieldKey] !== $fieldVlaue) {
                        $text .= self::title . "【{$info['id']}】非已发货状态，无法删除<br>";
                        continue;
                    }
                    $all = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($all['array'] as $val) {
                        fileDelete($val['src']);
                        delete(array("table" => 'file', "where" => " id = '$val[id]' "));
                    }
                    //添加主表ID到附件表
                    if (is_array($fileIdArr)) {
                        if ($x == 0) {
                            update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                        } else {
                            //复制附件记录
                            $files = find(array("table" => "file", "where" => " id in ('" . implode("','", $fileIdArr) . "') "));
                            foreach ((array)$files['array'] as $arr) {
                                $arr['id']       = self::getId();
                                $arr['targetId'] = $id;
                                insert(array(
                                    'table' => 'file',
                                    'field' => $arr
                                ));
                            }
                        }
                    }
                    update(array('table' => self::table, 'field' => ['send_state' => 3, 'receipt_date' => $this->post('receipt_date'), 'receipt_text' => $this->post('receipt_text')], 'where' => "id = '$info[id]'"));
                    //添加记录
                    $text .= "{$this->control['name']}操作了回单登记" . self::title . "：ID【{$id}】" . ($info['orderNo'] ? "，发货单号【{$info['orderNo']}】" : '') . '<br>';
                    $x++;
                }
            }

            // 写入日志
            $this->logText(["type" => 'deliveryManageDelivery', "text" => $text]);
            $_SESSION['warn'] = "操作了{$x}条" . self::title . "的回单登记";
            $json['warn']     = 2;
            //$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=delivery";
        }

        resp:
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function signOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('已签收');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*发货列表-查询条件*/
    public function sign(): string
    {
        $html = $this->signOptions(false);
        $button = "";
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 已签收
     * @return bool|string
     */
    public function signSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "orderNo"     => $this->post('orderNo'),
            "contactName" => $this->post('contactName'),
            "contactTel"  => $this->post('contactTel'),
            "address"     => $this->post('address'),
        );
        //全等查询数组
        $equal = array(
            'coid'       => self::$coid,
            'send_state' => 3,  //已发货
            "manager"    => $this->post('stid'),
        );

        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'));
        }
        if ($this->post('contractName')) {
            $and2 = " and name like '%" . $this->post('contractName') . "%' ";
            $and  .= " and contractId in (select id from sales_contract where 1=1 {$and2}) ";
        }
        if ($this->post('carInfo')) {
            $and .= " and id in (select orderId from sale_send_order_car where car_no like '%" . $this->post('carInfo') . "%' or driver like '%" . $this->post('carInfo') . "%' or contactTel like '%" . $this->post('carInfo') . "%') ";
        }
        if ($this->post('unitA')) {
            $and .= " and khid in (select khid from kehu where companyName like '%" . $this->post('unitA') . "%') ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $obj = new performanceScoreClass();
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate       = array(
                "box"    => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'sales_contract':
                        $sales_contract = query("sales_contract", " id = '" . $array['contractId'] . "' ");
                        $row[] = $sales_contract['name'];
                        break;
                    case 'companyName':
                        $kehu           = query("kehu", " khid = '" . $array['khid'] . "' ", 'companyName');
                        $row[] = $kehu['companyName'];
                        break;
                    case 'carInfo':
                        $carInfo        = $this->carInfo($array['id']);
                        $row[] = $carInfo;
                        break;
                    case 'total':
                        $total          = find(['table' => 'sale_send_order_car', 'sum' => 'actual_weight', 'single' => " orderId = '$array[id]' "]);
                        $row[] = $total;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $total    = [
            'total'        => self::lostZero(
                find(['table' => 'sale_send_order_car', 'sum' => 'actual_weight', 'single' => " orderId in (select id from ".self::table." where 1=1 {$where}) "]),
                'numPrecision'
            ),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


}
